import router from '@/router'
//@ts-ignore
import nprogress from 'nprogress'
import "nprogress/nprogress.css"
nprogress.configure({showSpinner: false})
//引入用户仓库
import pinia from './store'
import useUserStore from './store/modules/user'
let userStore = useUserStore(pinia)

//全局前置守卫
router.beforeEach(async(to,from,next)=>{
    document.title = to.meta.title+'-商户后台管理系统'
    nprogress.start()
    let token = userStore.token
    let username = userStore.username
    if(token){
        //登录
        if(to.path == '/login'){
            next({path:'/'})
        }else{
            if(username){
                next()
            }else{
                try {
                    await userStore.userInfo()
                    next()
                } catch (error) {
                    //token过期或者用户手动修改token
                    await userStore.userLogout()
                    next({path:'/login',query:{redirect:to.path}})
                }
            }
        }
    }else{
        //未登录
        if(to.path == '/login'){
            next()
        }else{
            next({path:'/login',query:{redirect:to.path}})
        }
    }
})

//全局后置守卫
router.afterEach((to,from)=>{
    nprogress.done()
})


//进度条  npm i nprogress安装